package com.example.demo.mapper;

import com.example.demo.entity.Chapter;
import org.apache.ibatis.annotations.*;
import java.util.List;
import java.util.Optional;

@Mapper
public interface ChapterMapper {

    // 完整的列名列表，方便后续修改
    String COLUMNS = "chapter_id, course_id, chapter_name, chapter_order, description, chapter_level, created_at, updated_at";

    // 1. 查找所有章节
    @Select("SELECT " + COLUMNS + " FROM chapters")
    List<Chapter> findAll();

    // 2. 根据 ID 查找单个章节
    @Select("SELECT " + COLUMNS + " FROM chapters WHERE chapter_id = #{chapterId}")
    Optional<Chapter> findById(@Param("chapterId") Integer chapterId);

    // 3. 根据课程 ID 查找所有章节，并按 chapter_order 排序 (利用 idx_course_order 索引)
    @Select("SELECT " + COLUMNS + " FROM chapters WHERE course_id = #{courseId} ORDER BY chapter_order ASC")
    List<Chapter> findByCourseIdOrderByOrder(@Param("courseId") String courseId);

    // 4. 插入新章节
    @Insert("INSERT INTO chapters (course_id, chapter_name, chapter_order, description, chapter_level) " +
            "VALUES (#{courseId}, #{chapterName}, #{chapterOrder}, #{description}, #{chapterLevel})")
    // 使用 Options 获取自增主键的值，并设置回 Chapter 对象的 chapterId 属性
    @Options(useGeneratedKeys = true, keyProperty = "chapterId")
    int insert(Chapter chapter);

    // 5. 更新章节信息
    @Update("UPDATE chapters SET course_id = #{courseId}, chapter_name = #{chapterName}, " +
            "chapter_order = #{chapterOrder}, description = #{description}, chapter_level = #{chapterLevel} " +
            "WHERE chapter_id = #{chapterId}")
    int update(Chapter chapter);

    // 6. 根据 ID 删除章节
    @Delete("DELETE FROM chapters WHERE chapter_id = #{chapterId}")
    int deleteById(@Param("chapterId") Integer chapterId);
}